<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="资料名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入资料名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="资料备注" prop="remark">
        <el-input v-model="queryParams.remark" placeholder="请输入资料备注" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="校区" prop="schoolName">
        <el-input v-model="queryParams.schoolName" readonly="readonly" @click.native="openSelectSchool(1)"
          placeholder="请输入校区" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="UNIT" prop="unitName">
        <el-input v-model="queryParams.unitName" @click.native="openSelectCourse(1)" :readonly="true"
          placeholder="点此选择UNIT" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['school:archives:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['school:archives:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['school:archives:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="archivesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="资料名称" align="center" prop="name" />
      <el-table-column label="资料备注" align="center" prop="remark" />
      <el-table-column label="UNIT" align="center" prop="unitName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-down" @click="down(scope.row)">下载</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['school:archives:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改学校资料对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="资料名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入资料名称" />
        </el-form-item>
        <el-form-item label="资料备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入资料备注" />
        </el-form-item>
        <el-form-item label="UNIT" prop="unitName">
          <el-input v-model="form.unitName" @click.native="openSelectCourse(2)" :readonly="true"
            placeholder="点此选择UNIT" />
        </el-form-item>
        <el-form-item label="资料" prop="fileName">
          <file-upload v-model="form.fileName" :fileType="null" :limit="1" :fileSize="100"
            :data="{'relationType':'SCHOOL_ARCHIVES'}" @success="handleFileSuccess" @remove="handleFileRemove"
            @error="handleFileError" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" @keyup.enter.native="submitForm"
          :loading="submitLoading">{{ submitLoading ? '提交中...' : '确定' }}</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 选择学校 -->
    <SelectSchool ref="selectSchool" :open="selectFlag" @selected-data="selectSchoolData"
      @close-select-window="closeSelectSchool" />
    <select-course ref="selectCourseRef" @selected-data="selectedCourseData"></select-course>
  </div>
</template>

<script>
  import {
    listArchives,
    getArchives,
    delArchives,
    addArchives,
    updateArchives
  } from "@/api/bus_web/school/archives";
  import {
    mapState
  } from 'vuex';
  import store from "@/store";
  import SelectSchool from "../schoolinfo/select.vue"
  import SelectCourse from "../../course/course/select.vue"
  export default {
    name: "Archives",
    components: {
      SelectSchool,
      SelectCourse
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 是否显示学校选择
        selectFlag: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 提交处理中标记
        submitLoading: false,
        // 总条数
        total: 0,
        // 学校资料表格数据
        archivesList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: null,
          remark: null,
          type: null,
          schoolId: null,
          schoolId: null,
          schoolIdArray: [],
          schoolName: null,
          fileId: null,
          unitIdArray: [],
          unitName: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          name: [{
            required: true,
            message: "资料名称不能为空",
            trigger: "blur"
          }],
          fileName: [{
            required: true,
            message: "资料不能为空",
            trigger: "blur"
          }],
          unitName: [{
            required: true,
            message: "UNIT不能为空",
            trigger: "change"
          }],
        }
      };
    },
    created() {
      this.getList();
    },
    computed: {
      ...mapState({
        school: state => state.selectSchool.school,
        schoolSelectModel: state => state.selectSchool.schoolSelectModel,
        course: state => state.selectCourse.course,
        courseSelectModel: state => state.selectCourse.courseSelectModel,
      })
    },
    methods: {
      /** 查询学校资料列表 */
      getList() {
        this.loading = true;
        listArchives(this.queryParams).then(response => {
          this.archivesList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          name: null,
          remark: null,
          schoolName: null,
          type: null,
          schoolId: null,
          fileId: null,
          fileName: null,
          gmtCreate: null,
          gmtModify: null,
          createBy: null,
          updateBy: null,
          deleted: null,
          unitName: null,
          unitId: null
        };
        this.resetForm("form");
        this.form.unitId = null
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.queryParams.unitIdArray = []
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加学校资料";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getArchives(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改学校资料";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.submitLoading = true
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateArchives(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.submitLoading = false
              })
            } else {
              addArchives(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.submitLoading = false
              })
            }
          } else {
            this.submitLoading = false
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除学校资料编号为"' + ids + '"的数据项？').then(function() {
          return delArchives(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('school/archives/export', {
          ...this.queryParams
        }, `archives_${new Date().getTime()}.xlsx`)
      },
      //选择学校
      openSelectSchool(selectVal) {
        this.selectFlag = true
        // selectVal =1 查询模式 =2 创建、修改模式
        this.$store.dispatch('selectSchool/cleanSchool')
        this.$store.dispatch('selectSchool/setSchoolSelectModel', selectVal)
      },
      closeSelectSchool() {
        this.selectFlag = false
      },
      //确定学校
      selectSchoolData() {
        this.closeSelectSchool()
        if (this.schoolSelectModel == 2) {
          this.form.schoolName = this.school[0].schoolName
          this.form.schoolId = this.school[0].id
          this.$refs.form.clearValidate(['schoolName']);
        } else {
          this.queryParams.schoolName = this.school.map(item => item.schoolName).join(',')
          this.queryParams.schoolIdArray = this.school.map(item => item.id)
        }
        this.$store.dispatch('selectSchool/cleanSchool')
      },
      // 上传成功回调
      handleFileSuccess(files) {
        for (var i in files) {
          this.$set(this.form, "name", files[i].name)
          this.$set(this.form, "fileId", files[i].id)
        }
      },

      // 删除文件回调
      handleFileRemove(files) {},

      // 上传失败或校验失败回调
      handleFileError(error) {

      },
      down(row) {
        let formData = {
          'fileName': row.url
        }
        this.download('school/archives/downArchives', {
          ...formData
        }, row.fileName)
      },
      //选择课程
      openSelectCourse(selectVal) {
        if (selectVal == 1) {
          this.$nextTick(() => {
            // selectVal =1 查询模式 =2 创建、修改模式
            this.$store.dispatch('selectCourse/cleanCourse')
            this.$store.dispatch('selectCourse/setCourseSelectModel', selectVal)
            this.$refs.selectCourseRef.init(this.form.level)
          })
          return
        } else {
          this.$store.dispatch('selectCourse/cleanCourse')
          this.$store.dispatch('selectCourse/setCourseSelectModel', selectVal)
          this.$refs.selectCourseRef.init()
        }
      },
      //确定课程
      selectedCourseData() {
        if (this.courseSelectModel == 2) {
          this.form.unitName = this.course[0].name
          this.form.unitId = this.course[0].id
          this.$refs.form.clearValidate(['unitName']);
        } else {
          this.queryParams.unitName = this.course.map(item => item.name).join(',')
          this.queryParams.unitIdArray = this.course.map(item => item.id)
        }
        this.$store.dispatch('selectCourse/cleanCourse')
      }
    }
  };
</script>
